package com.neuedu.utils;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DBUtil {

    /**
     * 封装执行任意SQL的方法
     */
    public static List<Map<String,Object>> exeSQL(String sql,Object ... params){
        List<Map<String,Object>> result=new ArrayList<>();
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs =null;
        try {
            conn=getConnection();
            ps= conn.prepareStatement(sql);
            if(params!=null) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }
            rs=ps.executeQuery();
            while (rs.next()){
                //指向下一行
                Map<String,Object> map=new HashMap<>();
                for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
                    String columnName=rs.getMetaData().getColumnName(i+1);
                    Object columnValue = rs.getObject(columnName);
                    map.put(columnName,columnValue);
                }
                result.add(map);
            }
            return result;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            close(rs,ps,conn);
        }
        return result;
    }



    /**
     * 获取数据库连接的方法
     *
     * @return
     */
    public static Connection getConnection() {

        return ConnectionPool.getConnection();
    }

    /**
     * 关闭资源的方法
     *
     * @param rs
     * @param st
     * @param conn
     */
    private static void close(ResultSet rs, Statement st, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        close(st, conn);
    }

    private static void close(Statement st, Connection conn) {
        if (st != null) {
            try {
                st.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        close(conn);
    }

    private static void close(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


    /**
     * 更新数据的通用方法
     *
     * @param object 要更新的内容 无论内部的数据是什么，都更新，一行数据全量更新
     * @param where  更新的条件 形如  id=?
     * @param params 条件？填充的内容
     * @param <T>
     * @return
     */
    public static <T> int update(T object, String where, Object... params) {
        Class<?> clazz = object.getClass();
        String tableName = clazz.getSimpleName();
        Field[] fields = clazz.getDeclaredFields();
        Connection conn=null;
        PreparedStatement ps=null;
        try {
            String setSpace="";
            List<Object> values=new ArrayList<>();
            for (int i = 0; i < fields.length; i++) {
                fields[i].setAccessible(true);
                String name = fields[i].getName();
                Object value = fields[i].get(object);
                values.add(value);
                setSpace=setSpace+name+"=?,";
            }
            //去掉逗号
            setSpace=setSpace.substring(0,setSpace.length()-1);
            String sql="update "+tableName+" set "+setSpace+" where "+where;
            //setSpace里的？用values进行填充，where里的？用params填充，总体上？的角标从1开始不间断。
            int index=0;
            conn=getConnection();
            ps=conn.prepareStatement(sql);
            //替换？
            for (int i = 0; i < values.size(); i++,index++) {
                ps.setObject(index+1,values.get(i));
            }
            for (int i = 0; i < params.length; i++,index++) {
                ps.setObject(index+1,params[i]);
            }
            int result = ps.executeUpdate();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            close(ps,conn);
        }
        return 0;
    }

    /**
     * 更新数据的通用方法
     *
     * @param object 要更新的内容 object里的值代表了要更新的数据，如果为null就认为是不更新。
     *               这叫选择性的更新一行数据里的局部字段
     * @param where  更新的条件 形如  id=?
     * @param params 条件？填充的内容
     * @param <T>
     * @return
     */
    public static <T> int updateSelective(T object, String where, Object... params) {
        //student
        //update student set sid=1,sname="张三" ....   where sid=?
        Class<?> clazz = object.getClass();
        String tableName = clazz.getSimpleName();
        Field[] fields = clazz.getDeclaredFields();
        Connection conn=null;
        PreparedStatement ps=null;
        try {
            String setSpace="";
            List<Object> values=new ArrayList<>();
            for (int i = 0; i < fields.length; i++) {
                fields[i].setAccessible(true);
                String name = fields[i].getName();
                Object value = fields[i].get(object);
                if(value==null){
                    continue;
                }
                values.add(value);
                setSpace=setSpace+name+"=?,";
            }
            //去掉逗号
            setSpace=setSpace.substring(0,setSpace.length()-1);
            String sql="update "+tableName+" set "+setSpace+" where "+where;
            //setSpace里的？用values进行填充，where里的？用params填充，总体上？的角标从1开始不间断。
            int index=0;
            conn=getConnection();
            ps=conn.prepareStatement(sql);
            //替换？
            for (int i = 0; i < values.size(); i++,index++) {
                ps.setObject(index+1,values.get(i));
            }
            for (int i = 0; i < params.length; i++,index++) {
                ps.setObject(index+1,params[i]);
            }
            int result = ps.executeUpdate();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            close(ps,conn);
        }
        return 0;
    }


    /**
     * 删除数据的通用方法
     *
     * @param clazz  类对象，用于确认表名
     * @param where  删除的条件 形如：id=?
     * @param params ?被替换的内容
     * @param <T>
     * @return
     */
    public static <T> int delete(Class<T> clazz, String where, Object... params) {
        String tableName = clazz.getSimpleName();
        String sql = "delete from " + tableName + " where " + where;
        Connection conn = getConnection();
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
            int result = ps.executeUpdate();
            return result;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            close(ps, conn);
        }
        return 0;
    }


    /**
     * 插入数据的通用方法
     *
     * @param object
     * @param <T>
     * @return
     */
    public static <T> int insert(T object) {
        //根据对象获取类名（表名）
        Class<?> clazz = object.getClass();
        //获取所有成员
        Field[] fields = clazz.getDeclaredFields();
        //假如object是一个student{sname="张三",sage=18}
        //insert into student(sname,sage) values("张三",18);

        //insert into student(sid,sname,sage,ssex) values(101,"张三",18,"男");


        //insert into student(sid,sname,sage,ssex) values(?,?,?,?);
        String columnName = "";
        String lastSpace = "";
        List<Object> columnValues = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            for (int i = 0; i < fields.length; i++) {
                fields[i].setAccessible(true);
                //获取字段名和字段值
                String colName = fields[i].getName();
                Object colValue = fields[i].get(object);
                if (colValue == null) {
                    continue;
                }
                columnName = columnName + colName;
                lastSpace = lastSpace + "?";
                columnValues.add(colValue);

                columnName = columnName + ",";
                lastSpace = lastSpace + ",";

            }
            //祛痘
            columnName = columnName.substring(0, columnName.length() - 1);
            lastSpace = lastSpace.substring(0, lastSpace.length() - 1);


            String sql = "insert into " + clazz.getSimpleName() + "(" + columnName + ") values (" + lastSpace + ")";
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < columnValues.size(); i++) {
                ps.setObject(i + 1, columnValues.get(i));
            }
            int result = ps.executeUpdate();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(ps, conn);
        }
        return 0;
    }


    public static <T> T findOneByWhere(Class<T> clazz, String where, Object... params) {
        //1、拿到类名，成员名
        String tableName = clazz.getSimpleName();
        //2、拿到所有的成员名，用，分隔。
        Field[] fields = clazz.getDeclaredFields();
        String colNames = "";
        for (int i = 0; i < fields.length; i++) {
            //设置可见性为true
            fields[i].setAccessible(true);
            String name = fields[i].getName();
            colNames = colNames + name;
            if (i != fields.length - 1) {
                colNames = colNames + ",";
            }
        }
        String sql = "select " + colNames + " from " + tableName + " where " + where;

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            //应该替换？位置，用params数组里的内容来替换
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
            rs = ps.executeQuery();
            if (rs.next()) {
                T object = clazz.newInstance();
                for (int i = 0; i < fields.length; i++) {
                    //假如field[i]是sid，那么从rs里取出的内容就是101=>value
                    //student  sid   101
                    //sid.set(student,101)
                    Object value = rs.getObject(fields[i].getName());
                    fields[i].set(object, value);
                }
                return object;
            } else {
                return null;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } finally {
            close(rs,ps,conn);
        }

        return null;
    }

    public static <T> List<T> findByWhere(Class<T> clazz, String where, Object... params) {
        List<T> list = new ArrayList<>();

        //1、拿到类名，成员名
        String tableName = clazz.getSimpleName();
        //2、拿到所有的成员名，用，分隔。
        Field[] fields = clazz.getDeclaredFields();
        String colNames = "";
        for (int i = 0; i < fields.length; i++) {
            //设置可见性为true
            fields[i].setAccessible(true);
            String name = fields[i].getName();
            colNames = colNames + name;
            if (i != fields.length - 1) {
                colNames = colNames + ",";
            }
        }
        String sql = "select " + colNames + " from " + tableName + " where " + where;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            //应该替换？位置，用params数组里的内容来替换
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
            rs = ps.executeQuery();
            while (rs.next()) {
                T object = clazz.newInstance();
                for (int i = 0; i < fields.length; i++) {
                    //假如field[i]是sid，那么从rs里取出的内容就是101=>value
                    //student  sid   101
                    //sid.set(student,101)
                    Object value = rs.getObject(fields[i].getName());
                    fields[i].set(object, value);
                }
                list.add(object);
            }
            return list;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } finally {
            close(rs,ps,conn);
        }

        return null;
    }


    /**
     * 封装一个方法，去查询数据库。
     * 这个方法参数是Student.class   返回值是List<Student>
     */
    public static <T> List<T> findAll(Class<T> clazz) {
        List<T> list = new ArrayList<>();

        //1、拿到类名，成员名
        String tableName = clazz.getSimpleName();
        //2、拿到所有的成员名，用，分隔。
        Field[] fields = clazz.getDeclaredFields();
        String colNames = "";
        for (int i = 0; i < fields.length; i++) {
            //设置可见性为true
            fields[i].setAccessible(true);
            String name = fields[i].getName();
            colNames = colNames + name;
            if (i != fields.length - 1) {
                colNames = colNames + ",";
            }
        }
        String sql = "select " + colNames + " from " + tableName;

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                T object = clazz.newInstance();
                for (int i = 0; i < fields.length; i++) {
                    //假如field[i]是sid，那么从rs里取出的内容就是101=>value
                    //student  sid   101
                    //sid.set(student,101)
                    Object value = rs.getObject(fields[i].getName());
                    fields[i].set(object, value);
                }
                list.add(object);
            }
            return list;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } finally {
           close(rs,ps,conn);
        }

        return null;
    }
}
